package com.wu.leetcode.leetcode90;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Leetcode90-子集2
 * @author lynn
 * @date 2020/8/18 - 18:23
 */
public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return null;
        }
        Arrays.sort(nums);
        dfs(nums, 0, res, new ArrayList<Integer>());
        return res;
    }

    private void dfs(int[] nums, int index, List<List<Integer>> res, ArrayList<Integer> list) {
        if (index == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        if (index > 0 && nums[index] == nums[index - 1]) {
            return;
        }
        list.add(nums[index]);
        dfs(nums, index + 1, res, list);
        list.remove(list.size() - 1);
        while (index + 1 < nums.length && nums[index + 1] == nums[index]) {
            index++;
        }
        dfs(nums, index + 1, res, list);
    }
}
